package org.scratchcrew.services;

import org.scratchcrew.domain.Board;
import org.scratchcrew.domain.PrivateBoard;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Implementation of {@link securityService} interface. Uses BoardService and
 * UserService to map username with rights on board
 */
@Service(value = "securityService")
public class SecurityServiceImpl implements SecurityService {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	protected BoardService boardService;

	@Autowired
	protected UserService userService;

	public void setBoardService(BoardService boardService) {
		this.boardService = boardService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Override
	public boolean allowUserForBoard(final String userName, final long boardId) {
		final Board board = boardService.find(boardId);
		if (null == board) {
			// no such board
			return false;
		}

		// TODO howto check if board is private?
		if (board instanceof PrivateBoard) {
			// private board
			return isParticipantInPrivateBoard(userName, (PrivateBoard) board);
		} else {
			// public board - allow all user to join public board
			return true;
		}
	}

	private boolean isParticipantInPrivateBoard(final String userName,
			final PrivateBoard board) {
		if (null == userName) {
			// user should login in order to view private boards
			return false;
		}

		// TODO howto get participants in private board (now only owner can view
		// board)
		if (userName.equals(board.getOwner().getUserName())) {
			logger.debug(String.format("access granted: user %s for board %s",
					userName, board));
			return true;
		} else {
			logger.info(String.format("access denied: user %s for board %s",
					userName, board));
			return false;
		}
	}

}
